package com.icangya.DAO.impl;

import com.icangya.DAO.ICommissionFootDAO;
import com.icangya.domain.Commission;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Created by cangya5 on 2017/5/11.
 */
@Repository
public class CommissionFootDAOImpl extends BaseDAO<Commission> implements ICommissionFootDAO {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Commission selectUserCommis(String openId) {
        String hql = "FROM Commission comm where comm.openId = ? ";
        List<Commission> list = (List<Commission>) getHibernateTemplate().find(hql,openId);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }



    @Override
    public int changeMoney(String openId,double money) {
        int result = getHibernateTemplate().execute(new HibernateCallback<Integer>() {
            @Override
            public Integer doInHibernate(Session session) throws HibernateException {
                String hql = "UPDATE Commission commissionDO SET commissionDO.money =? , commissionDO.modifiedTime =?  WHERE commissionDO.openId =? ";
                Query queryupdate = session.createQuery(hql);
                Date now = new Date();
                queryupdate.setParameter(0, money);
                queryupdate.setParameter(1, new Timestamp(now.getTime()));
                queryupdate.setParameter(2,openId);

                int ret = queryupdate.executeUpdate();
                logger.warn("修改的用户为："+openId+"修改佣金为 == " + money + "|修改时间是 == " + new Timestamp(now.getTime()) + "|结果 == "
                        + ret);
                return ret;
            }
        });
        return result;
    }

//    @Override
//    public int caseMoney(String openId, double money) {
//
//
//        getHibernateTemplate().execute(new HibernateCallback<Integer>() {
//
//            @Override
//            public Integer doInHibernate(Session session) throws HibernateException {
//
//                String hql="update Commission comm set comm.money=money+?,";
//                return null;
//            }
//        });
//        return 0;
//    }


//    @Override
//    public Double sumCommissMoney(String openId) {
//        String hql = "select sum(commission.money) FROM Commission commission WHERE commission.openId = ?";
//        logger.info("hql" + hql);
//        List l = getHibernateTemplate().find(hql, openId);
//        if (l == null || l.size() == 0)
//            return 0.0;
//        Double value = (Double) l.get(0);
//        return value;
//    }




}
